﻿using System;
using System.Collections.Generic;

namespace DSAClient.Core
{
    /// <summary>
    /// 事件管理类
    /// </summary>
    public class AppReportManager
    {
        //单例模式.
        public static readonly AppReportManager Instance = new AppReportManager();
        private AppReportManager() { }

        //事件委托.
        public delegate void EventDelegate<T>(T e) where T : EventArgs;

        //保存所有事件<span style="font-family:Arial,Helvetica,sans-serif">接收方法</span>.
        readonly Dictionary<Type, Delegate> _delegates = new Dictionary<Type, Delegate>();

        //添加一个事件接收方法.
        public void AddListener<T>(EventDelegate<T> listener) where T : EventArgs
        {
            Delegate d;
            if (_delegates.TryGetValue(typeof(T), out d))
            {
                _delegates[typeof(T)] = Delegate.Combine(d, listener);
            }
            else
            {
                _delegates[typeof(T)] = listener;
            }
        }

        //删除一个事件接受方法
        public void RemoveListener<T>(EventDelegate<T> listener) where T : EventArgs
        {
            Delegate d;
            if (_delegates.TryGetValue(typeof(T), out d))
            {
                Delegate currentDel = Delegate.Remove(d, listener);

                if (currentDel == null)
                {
                    _delegates.Remove(typeof(T));
                }
                else
                {
                    _delegates[typeof(T)] = currentDel;
                }
            }
        }

        //发送事件.
        public void Send<T>(T e) where T : EventArgs
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            Delegate d;
            if (_delegates.TryGetValue(typeof(T), out d))
            {
                EventDelegate<T> callback = d as EventDelegate<T>;
                if (callback != null)
                {
                    callback(e);
                }
            }
        }
    }
}
